/** create by liuhua at 2018年7月16日 下午3:41:46 **/
package com.star.truffle.common.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerMapping;

import com.star.truffle.core.annotation.IgnoreSecurity;
import com.star.truffle.core.eureka.StarGateway;
import com.star.truffle.core.okhttp.StarOkHttpClient;
import com.star.truffle.core.util.MemoryCacheUtil;
import com.star.truffle.core.util.MemoryCacheUtil.CacheType;
import com.star.truffle.core.util.VerifyCodeUtils;
import com.star.truffle.core.web.ApiResult;

@Controller
public class CommonJumpController {

  @Autowired
  private StarOkHttpClient starOkHttpClient;
  
  @StarGateway
  @IgnoreSecurity
  @RequestMapping(value = "/image/verify", method = RequestMethod.GET)
  public void imageVerify(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String code = VerifyCodeUtils.outputVerifyImage(100, 40, response, 4);
    MemoryCacheUtil.put(CacheType.yzm, VerifyCodeUtils.VERIFY_CODES, code);
    System.out.println(code);
  }
  
  @RequestMapping(value = "/common/**", method = RequestMethod.GET)
  public String common(HttpServletRequest request) {
    String uriPath = extractPathFromPattern(request);
    return uriPath;
  }

  private static String extractPathFromPattern(final HttpServletRequest request) {
    String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
    return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
  }
  
  @StarGateway
  @IgnoreSecurity
  @ResponseBody
  @RequestMapping(value = "/open/url", method = RequestMethod.GET)
  public ApiResult<String> openUrl(String url) throws IOException {
    String html = starOkHttpClient.get(url);
    System.out.println(html);
    return ApiResult.success(html);
  }
}
